﻿using System;
using System.Xml.Serialization;

namespace Cubicle.Core.Config
{
    //[Serializable]
    //[XmlRoot(ElementName = "add")]
    //public class KvpElement<T>
    //{

    //    [XmlAttribute(AttributeName="key")]
    //    public string Key;

    //    [XmlAttribute(AttributeName = "value")]
    //    public T Value;

    //}

    [Serializable]
    [XmlRoot(ElementName = "add")]
    public class KvpElement
    {

        [XmlAttribute(AttributeName = "key")]
        public string Key;

        [XmlAttribute(AttributeName = "value")]
        public string Value;

        [XmlAttribute(AttributeName = "type")]
        public string TypeName
        {
            get { return _typeName; }
            set
            {
                _typeName = value;
                ReflectedType = Type.GetType(_typeName, false);
            }
        }

        [XmlIgnore]
        private string _typeName;

        [XmlIgnore]
        public Type ReflectedType { get; private set; }

        public T Get<T>()
        {
            return (T)Convert.ChangeType(Value, typeof (T));
        }

        public object Get()
        {
            return ReflectedType == null
                       ? null
                       : Convert.ChangeType(Value, ReflectedType);
        }

    }

}